import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Row, Col, Input, Button, Table, Card, message, Icon, Form, Modal, Spin, Tree, Checkbox, Switch, } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
import { getAuthority } from '@/utils/judgeAuthority';
const confirm = Modal.confirm;
import PageLoading from '@/components/PageLoading';
const { TreeNode } = Tree;
import styles from './index.less';
import MenuTree from '@/pages/Account/authManage/menuTree';
const AuthTree = React.lazy(() => import('./authTree'));
const Search = Input.Search;

const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
  class extends React.Component {
    checkField(rule, value, callback) {
      var reg = /^[0-9a-zA-Z_]{1,}$/g;
      if (rule.field === 'mail') {
        if (value) {
          if (reg.test(value)) {
            if (value.length > 30 || value.length < 6) {
              callback('支持6-30位大小写字母、数字和下划线');
            } else {
              callback();
            }
          } else {
            callback('支持6-30位大小写字母、数字和下划线');
          }
        } else {
          callback('');
        }
      } else {
        if (value) {
          callback();
        } else {
          callback('');
        }
      }
    }

    render() {
      const { visible, onCancel, onCreate, form, userInfo, isEdit, loading, treeMenuData, authority } = this.props;
      const { getFieldDecorator } = form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
      };

      return (
        <Modal visible={visible} title="添加角色" okText="保存" onCancel={onCancel} onOk={onCreate} okButtonProps={{ disabled: authority === 1 }}>
          <Spin spinning={loading}>
            <Form {...formItemLayout}>
              <Form.Item label="角色名称">
                {getFieldDecorator('roleName', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    { required: true, message: '请输入角色名称' },
                    { validator: this.checkField, },
                  ],
                })(<Input placeholder="请输入角色名称" disabled={authority === 1} />)}
              </Form.Item>
              <Form.Item label="角色说明">
                {getFieldDecorator('description', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    { required: true, message: '请输入角色说明' }
                  ]
                })(<Input.TextArea placeholder="请输入角色说明" disabled={authority === 1} />)}
              </Form.Item>
              <Form.Item label="菜单授权">
                {getFieldDecorator('menuTree')(
                  <MenuTree treeData={treeMenuData} onRef={ref => (this.MenuTree = ref)} authority={authority} />
                )}
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      );
    }
  }
);

@connect(({ authManage, loading }) => ({
  authManage,
  loading: loading.effects['authManage/getUsers'],
}))
class AuthManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      notices: [],
      tableLoading: true,
      total: 0,
      visible: false,
      searchText: '',
      userInfo: {},
      isEdit: false,
      loading: true,
      pageSize: 10,
      auth: true,
      jy: false,
      treeData: [],
      authList: [],
      roleId: '',
      defaultExpandedKeys: [],
      visible1: false,
      treeMenuData: [],
      editable: 1,
    };
    this.columns = [
      {
        key: 'roleName',
        align: 'left',
        title: '角色名称',
        dataIndex: 'roleName',
        width:200,
      },
      {
        key: 'description',
        align: 'left',
        title: '角色说明',
        dataIndex: 'description',
        width:200,
      },
      {
        key: 'updateTime',
        align: 'left',
        title: '创建时间',
        dataIndex: 'createTime',
        width:200,
        // render: dataIndex => {
        //   return moment(parseInt(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        // },
      },
      {
        title: '操作',
        align: 'left',
        width:200,
        fixed:"right",
        render: (text, row) => {
          return (
            <div>
              <Button
                type="primary"
                icon="edit"
                size="small"
                style={{ marginRight: 5 }}
                onClick={() => this.queryUser(row)}
              >
                设置
              </Button>
              <Button
                disabled={this.todo(row) || getAuthority(this.props.route.authority) === 1}
                type="danger"
                icon="close"
                size="small"
                style={this.qwe(row)}
                onClick={() => this.showDeleteConfirm(row)}
              >
                删除
              </Button>
            </div>
          );
        },
        width: '300px',
      },
    ];
  }

  componentDidMount() {
    this.getUsers();
    this.getmenusByUserIds();
  }

  showModal1 = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible1: true, loading: false, userInfo: {} });
  };

  handleCancel1 = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.formRef.MenuTree.resetCheckedKeys();
    this.setState({ visible1: false, isEdit: false });
  };

  handleCreate1 = () => {
    const form = this.formRef.props.form;
    const type = this.state.isEdit;
    const menuAccount = this.formRef.MenuTree.state.checkedKeys;
    console.log(menuAccount);
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      // console.log(type);
      if (type) {
        this.editUser(values, menuAccount);
      } else {
        this.addRole(values, menuAccount);
      }
    });
  };

  addRole = (values, menuAccount) => {
    let { dispatch, currentUser } = this.props;
    dispatch({
      type: 'authManage/addAuthRole',
      payload: {
        roleName: values.roleName,
        description: values.description,
        userStatus: 0,
        robotId: currentUser.robotId,
        menuId: menuAccount,
        userId: currentUser.uid
      },
      callback: res => {
        // console.log('新增', res);
        message.info(res.msg);
        this.getUsers();
        this.formRef.props.form.resetFields();
        this.formRef.MenuTree.resetCheckedKeys();
        this.setState({ visible1: false });
      },
    });
  }

  showModal = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: true, loading: false, userInfo: {} });
  };

  handleCancel = () => {
    this.setState({ visible: false, isEdit: false });
  };

  handleCreate = authList => {
    const that = this;
    that.setState({ visible: false, authList }, () => {
      that.addUser();
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  onChangeForPage = number => {
    this.setState({ page: number, tableLoading: true, }, () => {
      this.getUsers();
    });
  };

  fixRoleStatus = (status, row) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authManage/updateRoles',
      payload: { userStatus: status, roleId: row.roleId },
      callback: res => {
        if (!res.code) {
          message.info(res.msg);
          this.getUsers();
        } else {
          this.setState({ auth: false, });
        }
      },
    });
  };

  onShowSizeChangeForPage = (current, size) => {
    this.setState({ page: current, pageSize: size, tableLoading: true, }, () => {
      this.getUsers();
    });
  };

  getUsers = () => {
    const { dispatch, currentUser } = this.props;
    const { page, pageSize, searchText } = this.state;
    dispatch({
      type: 'authManage/getRoleLists',
      payload: { createUserId: currentUser.uid, page, rows: pageSize, roleName: searchText },
      callback: res => {
        this.setState({
          notices: res.list,
          total: parseInt(res.total),
          tableLoading: false,
        });
      },
    });
  };
  addUser1 = (obj, menuAccount) => {
    const form = this.formRef.props.form;
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'authManage/addRoles',
      payload: {
        roleName: obj.roleName,
        description: obj.description,
        menuId: menuAccount,
        userStatus: 0,
        userId: currentUser.uid,
        robotId: currentUser.robotId,
      },
      callback: res => {
        if (!res.code) {
          this.getUsers();
          message.info('添加成功');
          form.resetFields();
          this.setState({ visible1: false });
        }
      },
    });
  };
  addUser = () => {
    const { dispatch, currentUser } = this.props;
    const { roleId, authList } = this.state;

    dispatch({
      type: 'authManage/editAuthForRole',
      payload: { userId: currentUser.uid, roleId, menuIds: authList },
      callback: res => {
        if (res.code === '0') {
          this.getUsers();
        };
        message.info(res.msg);
      },
    });
  };

  delUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authManage/delRoles',
      payload: { roleId: row.roleId },
      callback: res => {
        if (!res.code) {
          message.info('执行成功');
          return this.getUsers();
        }
      },
    });
  };

  showDeleteConfirm = row => {
    const that = this;
    confirm({
      title: '确认删除【' + row.roleName + '】该角色吗',
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        that.delUser(row);
      },
      onCancel() { },
    });
  };

  resetUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'roleManagement/resetUser',
      payload: { userId: row._id },
      callback: res => {
        if (res.status) {
          return message.info(res.msg);
        };
        return message.error(res.msg);
      },
    });
  };

  editUser = (values, menuAccount) => {
    const { dispatch, currentUser } = this.props;
    const { userInfo } = this.state;
    dispatch({
      type: 'authManage/updateAuthRole',
      payload: {
        roleName: values.roleName,
        description: values.description,
        userStatus: 0,
        roleId: userInfo.roleId,
        menuId: menuAccount,
        userId: currentUser.uid
      },
      callback: res => {
        message.info(res.msg);
        this.getUsers();
        this.formRef.props.form.resetFields();
        this.formRef.MenuTree.resetCheckedKeys();
        this.setState({ visible1: false });
      },
    });
  };

  queryUser = row => {
    const { dispatch } = this.props;
    this.setState({ visible1: true, isEdit: true, loading: true, roleId: row.roleId, userInfo: row, });
    dispatch({
      type: 'authManage/getuserMenu',
      payload: { roleId: row.roleId },
      callback: res => {
        const form = this.formRef.props.form;
        form.setFieldsValue({ roleName: row.roleName })
        this.formRef.MenuTree.setChecked(res);
        this.setState({ authList: res, loading: false });
      },
    });
  };

  getmenusByUserIds = () => {
    let { dispatch, currentUser } = this.props;
    const that = this;
    dispatch({
      type: 'authManage/getAllSysMenu',
      payload: {
        userId: currentUser.uid
      },
      callback: res => {
        console.log('获取当前登陆用户的授权菜单', res);
        that.setState({ treeMenuData: res, });
      },
    });
  };

  setSearch = val => {
    this.setState({ searchText: val, page: 1, }, () => {
      this.getUsers();
    });
  };

  todo = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return true;
    }
  };

  sty = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5, backgroundColor: 'orange', color: '#fff' };
    }
  };

  qwe = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5 };
    }
  };

  setClassName = record => {
    return record.userStatus === '1' ? styles.grey : '';
  };

  render() {
    const { notices, tableLoading, page, total, pageSize, userInfo, isEdit, loading, treeMenuData, } = this.state;
    const { route } = this.props;

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Card bordered={false}>
            <div style={{ marginBottom: 10, borderBottom: '1px solid lightgrey', paddingBottom: 10 }}>
              <span style={{ fontSize: 16, color: '#000', borderLeft: '5px solid #13c2f3', paddingLeft: 10, }}>权限管理 ({total})</span>
            </div>
            <Row style={{ marginBottom: 10 }}>
              <Col span={4}>
                <Button
                  type="primary"
                  icon="plus"
                  style={{ marginRight: 5 }}
                  onClick={this.showModal1}
                  disabled={getAuthority(route.authority) === 1}
                >
                  添加角色
                </Button>
              </Col>
              <Col offset={16} span={4}>
                <Search placeholder="请输入角色名称" onSearch={value => this.setSearch(value)} />
              </Col>
            </Row>
            <div>
              <Table
                // rowClassName={this.setClassName}
                columns={this.columns}
                dataSource={notices}
                rowClassName={this.setClassName}
                rowKey="roleId"
                pagination={{
                  // 分页
                  total,
                  pageSize, // 显示几条一页
                  defaultPageSize: page, // 当前页
                  showSizeChanger: true, // 是否显示可以设置几条一页的选项
                  showQuickJumper: true,
                  onChange: this.onChangeForPage,
                  onShowSizeChange: this.onShowSizeChangeForPage,
                }}
                loading={tableLoading}
                scroll={{x:"auto"}}
              />
            </div>

            <CollectionCreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visible1}
              onCancel={this.handleCancel1}
              onCreate={this.handleCreate1}
              userInfo={userInfo}
              isEdit={isEdit}
              loading={loading}
              treeMenuData={treeMenuData}
              authority={getAuthority(route.authority)}
            />

            {/*<AuthTree*/}
            {/*  visible={this.state.visible}*/}
            {/*  onCancel={this.handleCancel}*/}
            {/*  onCreate={res => this.handleCreate(res)}*/}
            {/*  userInfo={this.state.treeData}*/}
            {/*  authList={this.state.authList}*/}
            {/*  loading={loading}*/}
            {/*  defaultExpandedKeys={this.state.defaultExpandedKeys}*/}
            {/*  treeData={this.state.treeData1}*/}
            {/*/>*/}
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AuthManage);
